<?php
declare(strict_types=1);


namespace App\Hoenix\Mapper;

use App\Hoenix\Model\HoenixIndex;
use App\Hoenix\Model\HoenixIndexAd;
use Hyperf\Database\Model\Builder;
use Mine\Abstracts\AbstractMapper;

/**
 * 广告列表Mapper类
 */
class HoenixIndexMapper extends AbstractMapper
{
    /**
     * @var HoenixIndex
     */
    public $model;

    public function assignModel()
    {
        $this->model = HoenixIndex::class;
    }

    /**
     * 搜索处理器
     * @param Builder $query
     * @param array $params
     * @return Builder
     */
    public function handleSearch(Builder $query, array $params): Builder
    {
        if (isset($params['status']) && filled($params['status'])) {
            $query->where('status', '=', $params['status']);
        }

        if (isset($params['type']) && filled($params['type'])) {
            $query->where('type', '=', $params['type']);
        }

        if (isset($params['type']) && filled($params['type'])) {
            $query->where('type', '=', $params['type']);
        }
//        $ids = HoenixIndexAd::query()
//            ->where(['shop_id' => redis()->hGet('adm:' . user()->getId(), 'main_shop_id')])
//            ->pluck('idx');
        return $query;//->whereIn('id', $ids);
    }

    public function save(array $data): mixed
    {
        $data['c_at'] = date('Y-m-d H:i:s');
        $id = parent::save($data);
        if ($id) {
            HoenixIndexAd::query()->create([
                'shop_id' => redis()->hGet('adm:' . user()->getId(), 'main_shop_id'),
                'idx' => $id,
            ]);
        }
        return $id;
    }

    public function delete(array $ids): bool
    {
        $s = parent::delete($ids);
        if ($s) {
            HoenixIndexAd::query()
                ->where(['shop_id' => redis()->hGet('adm:' . user()->getId(), 'main_shop_id')])
                ->whereIn('idx', $ids)->delete();
        }
        return $s;
    }
}